﻿using System;
using System.Collections.Generic;
using System.Text;

namespace FySystem.Extension
{
    public static class DoubleExtension
    {
        public enum EUnits
        {
            N = 0,
            K = 1,
            M = 2,
            G = 3,
            T = 4,
            P = 5
        }

        /// <summary>
        /// 单位转换
        /// </summary>
        /// <param name="val"></param>
        /// <param name="round"></param>
        /// <param name="unit"></param>
        /// <returns></returns>
        public static string[] ConvertUnits(this double? val, int round, EUnits unit, string baseUnit)
        {
            string[] res = null;
            try
            {
                val = val == null ? 0 : val;
                res = val.Value.ConvertUnits(round, unit, baseUnit);
            }
            catch (Exception)
            {
                throw;
            }
            return res;
        }

        /// <summary>
        /// 单位转换
        /// </summary>
        /// <param name="val"></param>
        /// <param name="round"></param>
        /// <param name="unit"></param>
        /// <param name="baseUnit"></param>
        /// <returns></returns>
        public static string[] ConvertUnits(this double val, int round, EUnits unit, string baseUnit)
        {
            string[] res = new string[2];
            try
            {
                double tmp = Math.Abs(val);
                int intVal = (int)unit;

                while (tmp >= 1000)
                {
                    tmp = tmp / 1000;
                    intVal += 1;
                }

                if (intVal == 0)
                    res[1] = baseUnit;
                else
                    res[1] = ((EUnits)intVal).ToString() + baseUnit;

                if (round == -1)
                    res[0] = tmp.ToString();
                else
                    res[0] = Math.Round(tmp, round, MidpointRounding.AwayFromZero).ToString();

                if (val < 0)
                    res[0] = $"-{res[0]}";
            }
            catch (Exception)
            {
                throw;
            }
            return res;
        }

        public static double NVL(this double? source, double dest = 0)
        {
            return source == null ? dest : source.Value;
        }

        /// <summary>
        /// 转换为Decimal
        /// </summary>
        /// <param name="source"></param>
        /// <param name="round">默认为-1，有多少位小数就返回多少位</param>
        /// <returns></returns>
        public static decimal ToDecimal(this double source,int round = -1)
        {
            if (round == -1)
                return (decimal)source;
            else
                return Math.Round((decimal)source, round, MidpointRounding.AwayFromZero);
        }
    }
}
